import requests
import json
import re
import encryptt
from urllib import parse

url = "http://ehall.xidian.edu.cn/gsapp/sys/wdcjapp/modules/wdcj/xscjcx.do"
wdcjapp_url = 'http://ehall.xidian.edu.cn/gsapp/sys/wdcjapp/*default/index.do'
login_url = "http://ids.xidian.edu.cn/authserver/login"
login_url1 = 'http://ehall.xidian.edu.cn/login?service=http://ehall.xidian.edu.cn/new/index.html&ticket=ST-162804-FhhN10Nvsc6iRyJo5Ubv1610851160221-7FcT-cas'


my_headers = {
      'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36',
      'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
      'Accept-Encoding': 'gzip',
      'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6,zh-TW;q=0.4'
}


data = {
    'querySetting':
    json.dumps([{
        "name": "CJXSZ",
        "caption": "成绩显示值",
        "linkOpt": "AND",
        "builderList": "cbl_String",
        "builder": "equal",
        "value": "86"
    }]),
    '_gotoFirstPage':
    'true'
}


def login(username, input_password):
    sss = requests.Session()
    r = sss.get(login_url, headers=my_headers)
    # with open('index.html', 'w', encoding='utf-8') as file_object:
    #     file_object.write(r.text)
    salt_reg = r'<input type="hidden" id="pwdEncryptSalt" value="(.*)" /><input'

    lt_reg = r'<input type="hidden" name="lt" id="lt" value="(.*)" /><input'
    execution_reg = r'<input type="hidden" id="execution" name="execution" value="(.*)" /></form>'
    # rmShown_reg = r'<input type="hidden" name="rmShown" value="(.*)"/>'

    salt = re.compile(salt_reg).findall(r.content.decode('utf-8'))[0]
    lt = re.compile(lt_reg).findall(r.content.decode('utf-8'))[0]
    execution = re.compile(execution_reg).findall(r.content.decode('utf-8'))[0]
    # print(salt, lt, execution)

    password = encryptt.encryptAES(input_password, salt)

    # print(password)

    my_data = {
        'username': username,
        'password': password,
        'lt': lt,
        'execution': execution,
        '_eventId': 'submit',
        'rememberMe': 'on',
        'cllt': 'userNameLogin',
        'dllt': 'generalLogin',
        'captcha': ''
    }

    # 登录后
    r = sss.post(login_url, headers=my_headers, data=my_data)
    reditList = r.history  # 可以看出获取的是一个地址序列
    # print(f'获取重定向的历史记录：{reditList}')
    # for item in reditList:
    # print(item.headers["location"])
    check_url = reditList[3].headers["location"]
    # print(check_url)
    ticket = parse.parse_qs(parse.urlparse(check_url).query)['ticket']
    # print(ticket)
    data = {
        'service': 'http://ehall.xidian.edu.cn/new/index.html',
        'ticket': ticket
    }
    # # 绕过ticket加密
    sss.get(url='http://ehall.xidian.edu.cn/login', params=data)
    sss.get(wdcjapp_url)
    return sss.cookies.get_dict()
    # return sss


def find_exam(sss, st, en):
    st = st*10
    en = en*10+1
    for k in range(st, en):
        value = k / 10
        if k % 10 == 0:
            value = int(k / 10)
        data = {
            'querySetting':
            json.dumps([{
                "name": "XNXQDM",
                "caption": "学年学期",
                "linkOpt": "AND",
                "builderList": "cbl_m_List",
                "builder": "m_value_equal",
                "value": "20202",
                "value_display": "2021春"
            }, {
                "name": "CJXSZ",
                "caption": "成绩",
                "linkOpt": "AND",
                "builderList": "cbl_String",
                "builder": "equal",
                "value": str(value)
            }]),
            'pageSize': '12',
            'pageNumber': '1'
        }

        # data = json.dumps(data)
        r = sss.post(url, data=data, json=data)
        res = r.json()
        # print(type(res))
        if res['datas']['xscjcx']['totalSize'] > 0:
            print(value, res['datas']['xscjcx']['rows'][0]['KCMC'])


if __name__ == '__main__':
    print(login('xx', 'xx'))
    # find_exam(sss, 70, 100)
